import Common from '../../common/common.js';
let common = new Common;
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties:{ 
    infor:{ 
      type:Object
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    width:307,
    height:534,
    catShopUrl: '', //名片海报
    imgUrl: common.imgUrl,
    isDisable: false,//防止多次点击
    cardName:'',
    cardPic:'', //背景图
    fontColor:'',//背景色
  }, 
  ready() { 
    this.setData({ 
      infor:this.data.infor,
    })
    console.log(this.data.infor)
    this.getInfo()//获取店铺信息
  }, 
  methods: {
    // 绘制商品名片
    canvasKapian() { 
      wx.getSetting({
        success: res => {
          console.log(res);
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: res => {
                this.canvasClick();
              },
              fail: err => {
                wx.showModal({
                  title: "提示",
                  content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
                  success: res => {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (res) => {
                          if (res.authSetting['scope.writePhotosAlbum']) {
                            this.canvasClick();
                          } else {
                            wx.showToast({
                              title: '获取权限失败,无法使用保存图片或视频到您的相册',
                              icon: 'none'
                            })
                          }
                        },
                      })
                    }
                  }
                })
              }
            })
          } else {
            this.canvasClick();
          }
        }
      })
    },
    canvasClick() {
      this.setData({
        isDisable: true
      })
      wx.showLoading({
        title: '名片生成中...',
      })
      let goodsPicUrl = (this.data.infor.goodsPicUrl || this.data.infor.goodsPic || this.data.infor.url).replace(":443", ''); 
      console.log(goodsPicUrl)
      let cardPic = this.data.cardPic.replace(":443",'');
      let image1 = this.localImge(goodsPicUrl);
      let image2 = this.localImge(this.data.wxCode);
    
      let arr = []
      if(cardPic == ""){
        arr = [image1, image2]
      }else{
        let image3 = this.localImge(cardPic);
        arr = [image1, image2, image3]
      }
      Promise.all(arr).then(res => {
        console.log(res); 
        let goodsPicUrl = res[0];
        let wxCode1 = res[1];
        let cardPic1 =  res[2];
        let top = 30;
        let left = 35
        const ctx = wx.createCanvasContext("shareKapian");
        ctx.setFillStyle("#ffffff");//填充颜色
        ctx.fillRect(0, 0, this.data.width, this.data.height);   //画布大小 
        if(cardPic == ''){
        }else{ // 背景图
          ctx.drawImage(cardPic1 || '', 0, 0, this.data.width, this.data.height);
        }
        // 商品图片   img,x,y,width,height 236
        ctx.drawImage(goodsPicUrl, left, top, 236, 315);
        // 商品名字
        ctx.setFontSize(16);
        ctx.font = 'bold'; 
        ctx.fillStyle= this.data.fontColor || "#000000";
        ctx.fillText(this.data.infor.goodsName || this.data.infor.name || '', left, 380);
        // whetherMemberPrice 1是有会员价 0没有会员价 
        if(this.data.infor.whetherMemberPrice == 1){//会员价
          ctx.setFontSize(12); 
          ctx.fillStyle=this.data.fontColor || "#666666";
          ctx.fillText("会员价", left, 400);
          ctx.fillStyle="#fea60f";
          ctx.fillText(this.data.infor.memberPrice || '', left + 40, 400);
          ctx.fillStyle=this.data.fontColor || "#666666";
          ctx.fillText("原价", left + 120, 400);
          ctx.fillStyle="#fea60f";
          ctx.fillText(this.data.infor.salePrice || '', left + 150, 400);
        }else{ // 没有会员价
          ctx.setFontSize(12); 
          ctx.fillStyle=this.data.fontColor || "#666666";
          ctx.fillText("价格", left, 400);
          ctx.fillStyle="#fea60f";
          ctx.fillText(this.data.infor.salePrice || '', left + 30, 400);
        }
        // 店铺名字
        ctx.setFontSize(15);
        ctx.font = 'bold'; 
        ctx.fillStyle=this.data.fontColor || "#333333";
        ctx.fillText(this.data.stroeInfo.storeName || '', left, 440);
        // 店员图标
        ctx.drawImage('/images/icon/icon-member.png', left, 460, 10,10);
        // 店主||店长||店员和名字
        ctx.setFontSize(12); 
        ctx.fillStyle=this.data.fontColor || "#333333";
        let  member = ''
        if(this.data.userInfo.userType == 4){
          member = '店主'
        }else  if(this.data.userInfo.userType == 5){
          member = '店长'
        }else  if(this.data.userInfo.userType == 6){
          member = '店员'
        } 
        ctx.fillText(member + '：' + this.data.userInfo.realName || '', left+20, 470);
        // 电话图标
        ctx.drawImage('/images/icon/icon-tel.png', left, 490, 10,10);
        // 电话
        ctx.setFontSize(12); 
        ctx.fillStyle=this.data.fontColor || "#333333"; 
        ctx.fillText('电话：' + this.data.userInfo.tel || '', left+20, 500);
        // 二维码 
        this.circleImg(ctx, wxCode1, 210,425,22)  
        ctx.setFontSize(9); 
        // 识别小程序码
        ctx.setFontSize(9); 
        ctx.fillStyle=this.data.fontColor || "#666666"; 
        ctx.fillText('识别小程序码', 200, 484);
        // 提示进入详情页 
        ctx.setFontSize(9); 
        ctx.fillStyle=this.data.fontColor || "#666666"; 
        ctx.fillText('进入该店的商品详情页', 180, 499);
  
        ctx.save();
        ctx.draw(false, () => {
          wx.canvasToTempFilePath({
            canvasId: "shareKapian",
            success: res => {
              console.log('成功', res.tempFilePath)
              wx.hideLoading(); 
              this.setData({
                catShopUrl: res.tempFilePath
              });
              this.downFn();
            },
            fail: err => {
              console.log('生成失败', err);
            }
          });
        });
      }).catch(err => {
        console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: '图片加载失败,请返回重试',
          icon: 'none'
        })
      })
    },
    //生成本地图片
    localImge: function (src) {
      console.log('src', src);
      return new Promise(function (resolve, reject) {
        wx.downloadFile({
          url: src,
          success: function (res) {
            resolve(res.tempFilePath);
          },
          fail: err => {
            reject(err)
          }
        });
      });
    },
    //保存图片
    downFn() {
      let imgurl = '';
      wx.showLoading({
        title: '保存中...',
      })
      imgurl = this.data.catShopUrl;
      wx.saveImageToPhotosAlbum({
        filePath: imgurl,
        success: res => {
          wx.hideLoading()
          wx.showToast({
            title: "保存成功，从相册中分享到朋友圈吧",
            icon: "none",
            duration: 4000
          });
          this.setData({
            isDisable: false
          })
          this.addNum();  //统计次数
        },
        fail: function (err) {
          this.setData({
            isDisable: false
          })
          console.log(err)
          if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {  
            wx.hideLoading();
            wx.showModal({
              title: "提示",
              content: '图片保存失败，您需要开启相册权限并且重新保存,是否开启?',
              success: res => {
                if (res.confirm) {
                  wx.openSetting({
                    complete: (res) => {
                      console.log(res);
                    },
                  })
                }
              }
            })
          }
        }
      });
    },
    addNum:function(){ 
      //type 1 活动名片 2商品名片 3店铺名片
      common.requestAjax('/api/user-service/v1/storeDownloadCount/addCardAmount?orgSeq='+getApp().globalData.shopInfo.orgSeq+'&type='+2, 'POST').then(res => {
      }).catch(err => {
        console.log(err);
      })
    },
    // 圆形图片
    circleImg: function (ctx, img, x, y, r) {
      ctx.save()
      ctx.beginPath()
      var d = 2 * r;
      var cx = x + r;
      var cy = y + r;
      ctx.arc(cx, cy, r, 0, 2 * Math.PI);
      ctx.clip();
      ctx.drawImage(img, x, y, d, d);
      ctx.restore()
    },
    // 点击放大
    prewImage() {
      wx.previewImage({
        urls: [this.data.wxCode],
        complete: (res) => {},
        current: this.data.wxCode,
        fail: (res) => {},
        success: (res) => {},
      })
    },
    // 向父组件发送值
    sendMesgToFather: function(){
        this.triggerEvent("sendEvent", "true"); // sendEvent自定义名称事件
    },
    // 获取基本信息
    getInfo: function(e) { 
      let data = {
        userId: app.globalData.userId,
        orgSeq: app.globalData.orgSeq
      }
      common.requestAjax('/api/user-service/v1/foreign/getUserAndStoreInfo', 'GET', data).then(res => {
        this.setData({
          stroeInfo: res.data.storeInfoDTO,
          userInfo: res.data.userInfoDTO,
        }) 
        this.getWxCode()//获取小程序码
        this.queryGoodsUsaCard()//获得背景图和背景色
      }).catch(err => {
        console.log(err);
      })
    },
    // 获取小程序码
    getWxCode() {
      let data = {
        //  ?orgseq=" + getApp().globalData.shopInfo.orgSeq + '&goodsId=' + this.data.infor.goodsId || this.data.infor.id
        page: "pages/shop/productDetil/index",
        type:2,//1活动分享   2商品分享 3 店铺分享
        sceneStr: this.data.infor.goodsId + ',' + getApp().globalData.shopInfo.orgSeq + ',' + getApp().globalData.userId ,
        appid: getApp().globalData.appId,
        secret: getApp().globalData.wx_code,
        width: 300,
        orgSeq: getApp().globalData.shopInfo.orgSeq,
        userId: getApp().globalData.userId,
        phone:this.data.userInfo.tel
      }
      common.requestAjax('/api/file-service/v1/share/appletCode', 'POST', data).then(res => {
        if (res.data.code) {
          let wxCode = res.data.url.replace(":443", '');
          this.setData({
            wxCode,
          })
        }
      }).catch(err => {
        console.log(err);
      })
    },
    //获得背景图和背景色
    queryGoodsUsaCard(){
      let data = {  
      }
      common.requestAjax('/api/user-service/v1/StoreCard/queryGoodsUsaCard', 'get', data).then(res => {
        if (res.data.code == 1) {  
          this.setData({
            cardName:res.data.result.cardName || '',
            cardPic:res.data.result.cardPic || '', //背景图
            fontColor:res.data.result.fontColor || '',//背景色
          })
        }
      }).catch(err => {
        console.log(err);
      })
    }
  }
})

 